# -*- coding: utf-8 -*-
import threading
from threading import Thread, Event
import time

from threading import Thread, Event
import time


# Code to execute in an independent thread
def countdown(n, started_evt):
    print('countdown starting')
    # started_evt.set()
    while n > 0:
        print('T-minus', n)
        n -= 1
        time.sleep(1)
        if n < 5:
            started_evt.set()
            print(f'2. started_evt.is_set(): {started_evt.is_set()}')


def evt_test():
    # Create the event object that will be used to signal startup
    started_evt = Event()
    # Launch the thread and pass the startup event
    print('Launching countdown')
    t = Thread(target=countdown, args=(10, started_evt))
    t.start()
    # Wait for the thread to start
    print(f'1. started_evt.is_set(): {started_evt.is_set()}')
    started_evt.wait()  # 主线程被阻塞，直到 started_evt.is_set()
    print('countdown is running')


import random


def producer(evt):
    while True:
        data = random.randint(1, 100)
        print(f"Produced: {data} data")
        evt.set()
        time.sleep(random.uniform(0.5, 2))


def consumer(evt):
    while True:
        evt.wait()
        data = random.randint(1, 100)
        print(f"Consumed: {data} data")

        evt.clear()
        time.sleep(random.uniform(0.5, 2))


class ConsumerThread(threading.Thread):
    def __init__(self, evt):
        super().__init__()
        self.evt = evt

    def run(self) -> None:
        while True:
            print("ConsumerThread starting")
            time.sleep(3)
            self.evt.clear()


def consumer_test():
    event = threading.Event()
    producer_thread = threading.Thread(target=producer, args=(event,))
    consumer_thread = threading.Thread(target=consumer, args=(event,))
    consumer2 = ConsumerThread(event)
    consumer2.start()
    consumer_thread.start()
    producer_thread.start()
    producer_thread.join()
    consumer_thread.join()



if __name__ == '__main__':
    # evt_test()
    consumer_test()
